import json

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import user_passes_test
from django.http import JsonResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.views.decorators.http import require_http_methods


@csrf_exempt
@require_http_methods(["POST"])
def api_register(request):
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        password2 = data.get('password2')
        email = data.get('email', '')
    except:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)

    # ✅ 基本验证
    if not username or not password:
        return JsonResponse({'error': 'Username and password are required'}, status=400)

    if password != password2:
        return JsonResponse({'error': 'Passwords do not match'}, status=400)

    if User.objects.filter(username=username).exists():
        return JsonResponse({'error': 'Username already exists'}, status=400)

    # ✅ 创建用户（Django 自动加密密码）
    try:
        user = User.objects.create_user(
            username=username,
            password=password,
            email=email
        )
        user.save()

        return JsonResponse({
            'success': True,
            'message': 'User registered successfully',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        }, status=201)

    except Exception as e:
        return JsonResponse({'error': f'Registration failed: {str(e)}'}, status=500)


@csrf_exempt
@require_http_methods(["POST"])
def api_login(request):
    try:
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
    except:
        return JsonResponse({'error': 'Invalid JSON'}, status=400)

    if not username or not password:
        return JsonResponse({'error': 'Username and password required'}, status=400)

    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)  # ← 设置 session，自动写入 Set-Cookie: sessionid=...
        return JsonResponse({
            'success': True,
            'message': 'Login successful',
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        })
    else:
        return JsonResponse({'error': 'Invalid credentials'}, status=401)


@csrf_exempt
@require_http_methods(["POST"])
def api_logout(request):
    logout(request)  # ← 清除 session
    return JsonResponse({
        'success': True,
        'message': 'Logout successful'
    })


def login_required_json(view_func):
    """
    自定义装饰器：未登录时返回 JSON 401，而不是重定向
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_authenticated,
        login_url=None,
        redirect_field_name=REDIRECT_FIELD_NAME
    )
    wrapped_view = actual_decorator(view_func)

    def _wrapper_view(request, *args, **kwargs):
        if not request.user.is_authenticated:
            return JsonResponse({
                'error': 'Authentication required',
                'detail': 'Please log in first.'
            }, status=401)
        return wrapped_view(request, *args, **kwargs)

    return _wrapper_view


@csrf_exempt
@login_required_json  # ← 使用自定义装饰器
@require_http_methods(["GET"])
def api_test(request):
    user = request.user

    # 🖨️ 打印到控制台（后端日志/调试）
    print("=" * 50)
    print("✅ [API TEST] 当前登录用户信息:")
    print(f"   ID: {user.id}")
    print(f"   Username: {user.username}")
    print(f"   Email: {user.email}")
    print(f"   Superuser: {user.is_superuser}")
    print(f"   Staff: {user.is_staff}")
    print("=" * 50)

    return JsonResponse({
        'success': True,
        'message': 'You are logged in.',
        'user_info': {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'is_superuser': user.is_superuser,
            'is_staff': user.is_staff,
            'date_joined': user.date_joined.isoformat() if user.date_joined else None,
        }
    })
